/**
 * Created by Kylin on 2016/12/6.
 */
import React, {Component} from 'react';
import {connect} from 'react-redux';
import Content from '../../../public/common/Content'
import TodoIntro from './TodoIntro';
import AddTodo from './AddTodo';
import TodoList from './TodoList';
import TabShow from './TabShow';

import {
    addTodo,
    completedTodo,
    setVisibilityFilter,
    VisibilityFilters,
    show
} from '../../../public/redux/actions'

class TodoApp extends Component {
    render() {
        const {dispatch, todos, visibilityFilter, showButton} = this.props;
        return (
            <Content>
                <TodoIntro className=""/>
                <div>
                    <AddTodo show={showButton} onAddClick={text => dispatch(addTodo(text))}/>
                    <TodoList todos={todos}
                              onTodoClick={index => dispatch(completedTodo(index))}
                              onShowClick={index => dispatch(show(index))}/>
                    <TabShow filter={visibilityFilter}
                             onFilterChange={filter => dispatch(setVisibilityFilter(filter))}/>
                </div>
            </Content>
        )
    }
}

function selectTodos(todos, filter) {
    switch (filter) {
        case VisibilityFilters.SHOW_ALL:
            return todos;
        case VisibilityFilters.SHOW_COMPLETED:
            return todos.filter(todo => todo.completed);
        case  VisibilityFilters.SHOW_ACTIVE:
            return todos.filter(todo => !todo.completed);
        default:
            return todos;
    }
}

const mapStateToProps = (state) => {
    return {
        todos: selectTodos(state.todos, state.visibilityFilter),
        visibilityFilter: state.visibilityFilter,
        showButton: state.showButton
    }
};

export default connect(mapStateToProps)(TodoApp);

// 按需加载
module.exports = connect(mapStateToProps)(TodoApp);